package user

import (
	"Web-Shop/models"
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"github.com/smartwalle/alipay"
)

func (c *UserController) HandleOrder() {
	c.TplName = "place_order.html"

	skuids := c.GetStrings("skuid")

	if len(skuids) == 0 {
		c.Redirect("/cart", 302)
		return
	}

	conn, err := redis.Dial("tcp", "47.111.181.52:6379")
	if err != nil {
		beego.Info("redis连接失败")
		return
	}
	defer conn.Close()

	goodsBuffer := make([]map[string]interface{}, len(skuids))

	totalPrice := 0
	totalCount := 0

	for index, skuid := range skuids {
		temp := make(map[string]interface{})
		id, _ := strconv.Atoi(skuid)

		goodsSku := &models.GoodsSKU{Id: id}
		orm.NewOrm().Read(goodsSku)
		temp["goods"] = goodsSku

		count, _ := redis.Int(conn.Do("hget", "cart_"+strconv.Itoa(c.User.Id), id))
		temp["count"] = count

		amount := goodsSku.Price * count
		temp["amount"] = amount

		totalCount += count
		totalPrice += amount

		goodsBuffer[index] = temp
	}

	c.Data["goodsBuffer"] = goodsBuffer
	var addrs []models.Address
	orm.NewOrm().QueryTable("Address").RelatedSel("User").Filter("User__Id", c.User.Id).All(&addrs)
	c.Data["addrs"] = addrs

	c.Data["totalPrice"] = totalPrice
	c.Data["totalCount"] = totalCount
	transferPrice := 10
	c.Data["transferPrice"] = transferPrice
	c.Data["realyPrice"] = totalPrice + transferPrice

	c.Data["skuids"] = skuids
}

func (c *UserController) AddOrder() {
	// 获取订单相关数据
	addrid, _ := c.GetInt("addrid")
	payId, _ := c.GetInt("payId")
	skuidstr := c.GetString("skuids")
	ids := skuidstr[1 : len(skuidstr)-1]

	skuids := strings.Fields(ids)

	totalCount, _ := c.GetInt("totalCount")
	transferPrice, _ := c.GetInt("transferPrice")
	realyPrice, _ := c.GetInt("realyPrice")

	resp := make(map[string]interface{})
	defer c.ServeJSON()

	if len(skuids) == 0 {
		resp["ok"] = false
		resp["msg"] = "传递参数非法"
		c.Data["json"] = resp
		return
	}

	// 开启事务
	o := orm.NewOrm()
	o.Begin()

	order := models.OrderInfo{
		OrderId:      time.Now().Format("20160102150405") + strconv.Itoa(c.User.Id),
		Orderstatus:  1,
		PayMethod:    payId,
		User:         c.User,
		TotalCount:   totalCount,
		TotalPrice:   realyPrice,
		TransitPrice: transferPrice,
	}

	addr := models.Address{
		Id: addrid,
	}
	// 获取订单收货地址
	o.Read(&addr)
	order.Address = &addr

	o.Insert(&order)

	conn, _ := redis.Dial("tcp", "47.111.181.52:6379")
	defer conn.Close()

	for _, skuid := range skuids {
		id, _ := strconv.Atoi(skuid)
		goods := models.GoodsSKU{
			Id: id,
		}

		i := 3

		for i > 0 {
			o.Read(&goods)

			var orderGoods models.OrderGoods
			orderGoods.GoodsSKU = &goods
			orderGoods.OrderInfo = &order

			count, _ := redis.Int(conn.Do("hget", "cart_"+strconv.Itoa(c.User.Id), id))

			if count > goods.Stock {
				resp["ok"] = false
				resp["msg"] = "商品库存不足"
				c.Data["json"] = resp
				o.Rollback()
				return
			}
			// 获取当前库存
			preCount := goods.Stock
			time.Sleep(time.Second * 5) //模拟时间仑片被抢

			orderGoods.Count = count
			orderGoods.Price = count * goods.Price

			o.Insert(&orderGoods)

			goods.Stock -= count
			goods.Sales += count

			updateCount, _ := o.QueryTable("GoodsSKU").
				Filter("Id", goods.Id).
				Filter("Stock", preCount).
				Update(orm.Params{"Stock": goods.Stock, "Sales": goods.Sales})

			if updateCount == 0 {
				beego.Info("888888888888888888888888888888888888888")
				beego.Info("i===>", i)
				if i > 0 {
					i -= 1
					continue
				}
				resp["ok"] = false
				resp["msg"] = "库存改变，订单提交失败"
				c.Data["json"] = resp
				o.Rollback()
				return
			} else {
				conn.Do("hdel", "cart_"+strconv.Itoa(c.User.Id), goods.Id)
				break
			}
		}
	}

	o.Commit()
	resp["ok"] = true
	resp["msg"] = "ok"
	c.Data["json"] = resp
}

func (c *UserController) Pay() {
	var aliPubKey = "MIIBIjANBgkqhkiG9w0BA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pJXJr2U2BisLrMPhHEBwE/W9BzVZfRFkuJL9fFnYbShWDXxAzVs8UPJN7pbAbf2qt6urIokHGy0waMn2dPbcHkwNe6qdmWwuRgj/NgLa0SQ0+p55sDC9P1ks+YhtzWoVuOLfUh5qH7XTOuZDZ3vSymvl7D4b8CgYEAyrBnsY9ZI/UOhst2CnYzkHlNXoBGDE6UK228pUHRjLZrruNlQi18h1a3OEJsAyPAuov19CyOgqjuXV+GTxLRjgE+wPIpM9JEdYM3P614h+fuLtad/EAQOSkN5cMXpZx+yL4IXuPSBZo2yhZNBuD+sKk7rk9XXrdV/8Nd6gSdA0cCgYEAsqfJx3S+gXhMDNn7iblJvnzV87sR/LvAcFiRNmoLvUa3YJNDNUSgI685u+30qlOfeOz5CcPBfYkjd4czXOebCNjxdYaLpjkYewiYaZWn81cYa1bFojOKusphCklFE9n0wpfFOZZHSQmMrcel15sQlztv93qirB4Ky8xAvy5XFvkCgYBhS2qLJjdw9jpB5DrGbNT1vfSwrzxwveuMKUILxdt0A0EPk2JQ8Qq84JhUrjWxECF8qqCm1BiYicTaF3eeT3c+BkT8U4IJuR5ZlmIX9ApOmruPyj/ODWZ8OcPNDeg0/Dkz3VyhSBTR0aQJP8k7yxcW8DWQx881zSW//yT+p7ZDEwKBgQDReCNoCiru9au4276ETRqDYpEkTGN2XGnBLg1//QcUBESgY3e315uvCMqe6ALavVIIOLYE1jvQ5JymLx2fOqkmBt6XjXdcCkAaz9qtwK1DsJfKZwMiTVwzKFswU9lkoQzgISA1UTXDMCOAU1KxQ8K7hHTgJzMG+kx/cDu4U+Qzcw=="

	var appId = "2016101400684659"
	var client = alipay.New(appId, aliPubKey, privateKey, false)

	var orderId = c.GetString("orderId")
	var totalPrice = c.GetString("totalPrice")

	var p = alipay.AliPayTradePagePay{}

	p.NotifyURL = "http://localhost:8080/xxxxx"
	p.ReturnURL = "http://localhost:8080/payCallback"
	p.Subject = "天天生鲜"
	p.OutTradeNo = orderId
	p.TotalAmount = totalPrice
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	var url, err = client.TradePagePay(p)
	if err != nil {
		log.Println(err)
	}
	var payURL = url.String()
	c.Redirect(payURL, 302)
}
func (c *UserController) PayCallback() {
	log.Println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
	c.Redirect("/orders", 302)
}

// 下单流程分析
// 1. 获取订单数据（地址ID,商品ID数组...）
// 2. 开启一个事务
// 		2.1 根据传来的订单数据获取完整订单记录 存入数据库 订单表
// 		2.2 循环商品ID数组 获取订单商品记录 存入数据库 订单商品表
//		2.2.1 获取商品的库存 临时存储
// 		2.3 判断商品的库存是否等于更新时的库存，相等时，更新商品的库存量以及销售量
//		2.4 删除购物车中的当前订单中的商品
// 3.如果一切ok,提交事务
